﻿using System.Windows.Controls;
using Gavel.Common.Component.Helper;
using Gavel.Common.Utilities.Const;
using Gavel.Common.Utilities.Model;
using Gavel.ModLink.Helper;
using Gavel.ModLink.ViewModel;

namespace Gavel.ModLink.Views;

/// <summary>
/// 报文视图
/// </summary>
public partial class MessageView
{
    /// <summary>
    /// 报文视图模型
    /// </summary>
    private readonly MessageViewModel _viewModel;

    /// <summary>
    /// 单例构造
    /// </summary>
    public MessageView()
    {
        InitializeComponent();
        _viewModel = (MessageViewModel)DataContext;
        ClientHelper.Instance.ReceivedEvent += AppendMessage;
        ClientHelper.Instance.SentEvent += AppendMessage;
        ClientHelper.Instance.SocketStatusChangedEvent += SocketStatusChanged;
    }

    /// <summary>
    /// 添加报文
    /// </summary>
    /// <param name="transmit">报文传输</param>
    private void AppendMessage(MessageTransmit transmit)
    {
        _viewModel.Messages.Add(transmit.Message);
        byte code;
        byte err;
        switch (transmit.Protocol)
        {
            case ProtocolType.Tcp:
                if (transmit.Data.Length < 9)
                {
                    return;
                }

                code = transmit.Data[7];
                err = transmit.Data[8];
                break;
            default:
                if (transmit.Data.Length < 3)
                {
                    return;
                }

                code = transmit.Data[1];
                err = transmit.Data[2];
                break;
        }

        if (code <= 80)
        {
            return;
        }

        NotifyHelper.Instance.Warning($"收到故障信息\n{(FaultCode)err}");
    }

    /// <summary>
    /// 套接字状态修改
    /// </summary>
    /// <param name="status">套接字状态</param>
    private void SocketStatusChanged(SocketStatus status)
    {
        // 遇到连接中状态表示套接字重连，需要清空报文记录
        if (status != SocketStatus.Connecting)
        {
            return;
        }

        _viewModel.Messages.Clear();
    }

    /// <summary>
    /// 报文内容修改事件
    /// </summary>
    /// <param name="sender">事件发送者</param>
    /// <param name="e">事件参数</param>
    private void ContentChanged(object sender, TextChangedEventArgs e)
    {
        TextBox box = (TextBox)sender;
        box.ScrollToEnd();
    }
}